package com.haohan.cloud.scm.common.tools.util;

import cn.hutool.core.exceptions.UtilException;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.haohan.cloud.scm.common.tools.constant.ToolsConstant;
import com.pig4cloud.pigx.common.core.util.R;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.time.format.DateTimeParseException;
import java.util.List;
import java.util.Map;

/**
 * @author dy
 * @date 2019/10/23
 */
@Slf4j
@UtilityClass
public class ExcelUtils {

    /**
     * excel文件读取
     *
     * @param file
     * @return
     */
    public <T> R<List<T>> transExcel(MultipartFile file, Map<String, String> headerMap, Class<T> clazz) {
        if (null == file) {
            return R.failed("未选择文件");
        }
        // 类型限制
        String name = file.getOriginalFilename();
        String suffix = "";
        if (StrUtil.isNotBlank(name) && name.contains(".")) {
            suffix = name.substring(name.lastIndexOf("."));
        }
        if (!StringUtils.equalsAny(suffix.toUpperCase(), ".XLS", ".XLSX")) {
            return R.failed("文件支持格式为:XLS/XLSX");
        }

        ExcelReader reader;
        try {
            reader = ExcelUtil.getReader(file.getInputStream());
            reader.setHeaderAlias(headerMap);
            int count = reader.getRowCount();
            if (count > ToolsConstant.MAX_IMPORT_ROW) {
                return R.failed("最大处理行数为".concat(String.valueOf(ToolsConstant.MAX_IMPORT_ROW)).concat("行。"));
            }
        } catch (Exception e) {
            log.debug(e.getMessage());
            return R.failed("选择文件不支持");
        }
        List<T> readAll;
        try {
            readAll = reader.readAll(clazz);
        } catch (UtilException | DateTimeParseException  ex) {
            log.debug(ex.getMessage());
            return R.failed("选择文件中日期格式有误, 请更正后重新导入。");
        } catch (Exception e) {
            log.debug(e.getMessage());
            return R.failed("选择文件中格式有误, 请更正后重新导入。");
        }
        if(readAll.isEmpty()){
            return R.failed("选择文件未填写信息, 请更正后重新导入。");
        }
        return RUtil.success(readAll);
    }

}
